<template>
	<view class="circle-container pageBg">
		<custom-nav-bar title="圈子"></custom-nav-bar>

		<!-- 发布对话框 -->
		<uni-popup ref="publishDialog" type="bottom" :mask-click="true">
			<view class="publish-dialog">
				<view class="dialog-header">
					<text class="title">撰写动态</text>
					<uni-icons type="close" size="24" color="#666" @click="closePublishDialog"></uni-icons>
				</view>
				<view class="dialog-content">
					<textarea class="publish-textarea" placeholder="分享你的精彩时刻..." placeholder-style="color: #999;"
						v-model="publishContent" auto-focus></textarea>
					<view class="image-upload-area">
						<view class="add-image" @click="selectImage">
							<uni-icons type="plus" size="32" color="#ccc"></uni-icons>
						</view>
						<image class="uploaded-img" v-for="(img, index) in uploadedImages" :key="index" :src="img"
							mode="aspectFill"></image>
					</view>
				</view>
				<view class="dialog-footer">
					<view class="cancel-btn" @click="closePublishDialog">取消</view>
					<view class="confirm-btn" @click="publishPost">发布</view>
				</view>
			</view>
		</uni-popup>

		<!-- 帖子列表 -->
		<view class="post-list" v-if="posts.length">
			<view class="post-card" v-for="(post, index) in posts" :key="post.id">
				<!-- 帖子头部 -->
				<view class="post-header">
					<image class="avatar" :src="post.userAvatar" mode="aspectFill"></image>
					<view class="user-info">
						<text class="username">{{ post.username }}</text>
						<text class="post-time"> {{ post.createTime }}</text>
					</view>
				</view>

				<!-- 帖子内容 -->
				<view class="post-content">{{ post.content }}</view>

				<!-- 图片区域 -->
				<view class="post-images" v-if="post.images">
					<image class="post-img" :src="post.images" mode="aspectFill" @click="previewImage(post.images)">
					</image>
				</view>

				<!-- 操作栏 -->
				<view class="post-footer">
					<view class="action-item" @click="toggleComments(post)">
						<uni-icons type="chatbubble" size="18" color="#666"></uni-icons>
						<text class="action-text">评论</text>
					</view>
				</view>

				<!-- 评论区 -->
				<view class="comment-section" v-if="post.showComments">
					<view class="comment-item" v-for="comment in compoents" :key="comment.id">
						<image class="comment-avatar" :src="comment.userAvatar" mode="aspectFill"
							@click="goPerson(comment)"></image>
						<view class="comment-content">
							<text class="comment-username">{{ comment.username }}</text>
							<text class="comment-text">{{ comment.content }}</text>
							<text class="comment-time">{{ comment.createTime }}</text>
						</view>
					</view>

					<!-- 评论输入 -->
					<view class="comment-input-area">
						<input class="comment-input" v-model="postComments" placeholder="说点什么..."
							placeholder-style="color: #999;" />
						<view class="send-btn" @click="commentsSend(post.id)">发送</view>
					</view>
				</view>
			</view>
		</view>

		<view v-else>暂无数据...</view>


		<!-- 悬浮发布按钮 -->
		<view class="floating-btn" @click="showPublishDialog">
			<uni-icons type="plusempty" size="28" color="#fff"></uni-icons>
		</view>
	</view>
</template>


<script setup>
	import {
		ref
	} from 'vue';

	import {
		apiPosts,
		apiGetPosts,
		apiComments,
		apiCommentsPosts
	} from "/api/apis.js"

	// 发布相关
	const publishDialog = ref(null);
	const publishContent = ref('');
	const uploadedImages = ref([]);


	const showPublishDialog = () => {
		publishDialog.value.open();
	};

	const closePublishDialog = () => {
		publishDialog.value.close();
	};


	// 选择并上传图片（仅一张）
	const selectImage = async () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'], // 推荐压缩图
			sourceType: ['album'],
			success: async (res) => {
				const tempFilePath = res.tempFilePaths[0];


				// 使用 uni.uploadFile 调用上传接口
				uni.uploadFile({
					url: "http://localhost:9090/files/upload",
					filePath: tempFilePath,
					name: 'file', // 根据后端字段调整，如 'image', 'file' 等
					success: (uploadRes) => {
						let data;
						data = JSON.parse(uploadRes.data);
						if (data.code === "200") {
							uploadedImages.value = [data.data];
							uni.showToast({
								title: '上传成功',
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: data.msg || '上传失败',
								icon: 'none'
							});
						}
					},
				});
			}
		});
	};

	// 发布帖子
	const publishPost = async () => {
		let user;
		let token;

		// #ifdef MP
		token = uni.getStorageSync("token");
		user = uni.getStorageSync("userInfo");
		// #endif

		// #ifndef MP
		user = JSON.parse(uni.getStorageSync("userInfo") || "{}");
		token = user.token;
		// #endif

		if (!token) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			return;
		}

		if (!publishContent.value.trim() && uploadedImages.value.length === 0) {
			uni.showToast({
				title: '请输入内容或添加图片',
				icon: 'none'
			});
			return;
		}

		// ✅ 构造请求数据
		const postData = {
			content: publishContent.value,
			images: uploadedImages.value[0], // 已是服务器 URL 数组
			userId: user.id
		};

		const res = await apiPosts(postData)

		if (res.code === "200") {
			uni.showToast({
				title: '发布成功',
				icon: 'none'
			});

			const publishContent = "";
			const uploadedImages = [];

			closePublishDialog()

			loadPosts()

		}

	};


	// 切换评论显示
	const toggleComments = (post) => {
		post.showComments = !post.showComments;

		loadComments(post.id)
	};

	// 图片预览
	const previewImage = (urls) => {
		uni.previewImage({
			urls: [urls],
			current: urls,
			indicator: 'number',
		});
	};

	// 帖子数据（修复图片链接空格）
	const posts = ref([]);


	const loadPosts = async () => {
		const res = await apiGetPosts()
		posts.value = res.data
	}

	loadPosts()

	const postComments = ref(null)
	const commentsSend = async (id) => {

		let user;

		// #ifdef MP
		user = uni.getStorageSync("userInfo");
		// #endif

		// #ifndef MP
		user = JSON.parse(uni.getStorageSync("userInfo") || "{}");

		// #endif

		const data = {
			content: postComments.value,
			userId: user.id,
			postId: id
		}

		const res = await apiComments(data)

		if (res.code === "200") {
			uni.showToast({
				title: '评论成功',
				icon: 'none'
			});
			postComments.value = null

		}

	}

	const compoents = ref([])
	const loadComments = async (id) => {
		const res = await apiCommentsPosts(id)
		compoents.value = res.data
	}


	const goPerson = (user) => {
		uni.navigateTo({
			url: `/pagesMember/person/person?userId=${user.userId}`
		})
	}
</script>

<style lang="scss" scoped>
	/* 颜色变量 */
	$primary-color: #2979FF;
	$text-primary: #333;
	$text-secondary: #666;
	$text-muted: #999;
	$border-color: #f0f0f0;
	$bg-color: #f8f8f8;
	$radius-sm: 8rpx;
	$radius-md: 12rpx;
	$radius-lg: 16rpx;
	$shadow-sm: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	$shadow-md: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

	.circle-container {
		min-height: 100vh;
		background-color: $bg-color;
		padding-bottom: 120rpx;
	}

	/* 发布弹窗 */
	.publish-dialog {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: env(safe-area-inset-bottom);

		.dialog-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 28rpx 30rpx;
			border-bottom: 1rpx solid $border-color;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				color: $text-primary;
			}
		}

		.dialog-content {
			padding: 20rpx 30rpx;

			.publish-textarea {
				width: 100%;
				min-height: 200rpx;
				font-size: 28rpx;
				color: $text-primary;
				line-height: 1.6;
				margin-bottom: 20rpx;
			}

			.image-upload-area {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.add-image {
					width: 160rpx;
					height: 160rpx;
					border: 1rpx dashed #ddd;
					border-radius: $radius-md;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #fafafa;
				}

				.uploaded-img {
					width: 160rpx;
					height: 160rpx;
					border-radius: $radius-md;
					object-fit: cover;
					box-shadow: $shadow-sm;
				}
			}
		}

		.dialog-footer {
			display: flex;
			justify-content: space-between;
			padding: 24rpx 30rpx;
			border-top: 1rpx solid $border-color;

			.cancel-btn {
				width: 48%;
				height: 80rpx;
				background-color: #f5f5f5;
				border-radius: $radius-md;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: $text-secondary;
			}

			.confirm-btn {
				width: 48%;
				height: 80rpx;
				background-color: $primary-color;
				border-radius: $radius-md;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}

	/* 帖子列表 */
	.post-list {
		padding: 20rpx;
	}

	.post-card {
		background-color: #fff;
		border-radius: $radius-lg;
		margin-bottom: 24rpx;
		padding: 28rpx;
		box-shadow: $shadow-sm;
	}

	.post-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}

		.user-info {
			flex: 1;

			.username {
				font-size: 28rpx;
				font-weight: 500;
				color: $text-primary;
				margin-bottom: 4rpx;
			}

			.post-time {
				font-size: 24rpx;
				color: $text-muted;
			}
		}
	}

	.post-content {
		font-size: 28rpx;
		line-height: 1.6;
		color: $text-primary;
		margin-bottom: 20rpx;
		word-break: break-word;
	}

	.post-images {
		margin-bottom: 24rpx;

		.post-img {
			width: 100%;
			height: 400rpx;
			border-radius: $radius-md;
			object-fit: cover;
		}
	}

	.post-footer {
		display: flex;
		padding: 16rpx 0;
		border-top: 1rpx solid $border-color;

		.action-item {
			display: flex;
			align-items: center;
			margin-right: 40rpx;
			color: $text-secondary;

			.action-text {
				margin-left: 8rpx;
				font-size: 26rpx;
			}
		}
	}

	/* 评论区 */
	.comment-section {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid $border-color;

		.comment-item {
			display: flex;
			margin-bottom: 24rpx;

			.comment-avatar {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				margin-right: 16rpx;
			}

			.comment-content {
				flex: 1;

				.comment-username {
					font-size: 26rpx;
					color: $text-secondary;
					font-weight: 500;
					margin-right: 10rpx;
				}

				.comment-text {
					font-size: 26rpx;
					color: $text-primary;
				}

				.comment-time {
					display: block;
					font-size: 22rpx;
					color: $text-muted;
					margin-top: 6rpx;
				}
			}
		}

		.comment-input-area {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			.comment-input {
				flex: 1;
				height: 70rpx;
				background-color: #f5f5f5;
				border-radius: 35rpx;
				padding: 0 24rpx;
				font-size: 26rpx;
				color: $text-primary;
				margin-right: 16rpx;
			}

			.send-btn {
				color: $primary-color;
				font-size: 28rpx;
				font-weight: 500;
				padding: 0 24rpx;
			}
		}
	}

	/* 悬浮按钮 */
	.floating-btn {
		position: fixed;
		right: 32rpx;
		bottom: 80rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background-color: $primary-color;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: $shadow-md;
		z-index: 99;

		&:active {
			transform: scale(0.95);
		}
	}
</style>